<template>
    <div class="app-container">
        <el-row :gutter="12" style="margin-bottom: 20px">
            <el-col :lg="24" :xs="24">
                <el-card shadow="always">
                    <div slot="header" class="clearfix">
                        <span> {{$t("lab.programSetting")}}</span>
                        <el-button style="float: right; padding: 3px 0; margin-right: 10px" type="text" icon="el-icon-search" @click="findModel">{{$t("lab.findModel")}}</el-button>
                    </div>
                    <el-form ref="setting" label-width="auto" :inline="true">
                        <el-form-item :label="$t('lab.model')">
                            <el-select v-model="setting.model" filterable clearable :placeholder="$t('lab.modelTip')" @change="handleModelSelection" style="width: 100%" disabled>
                                <el-option v-for="item in setting.modelOptions" :key="item" :label="item" :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('lab.spindle')">
                            <el-select v-model="setting.spindle" filterable clearable :placeholder="$t('lab.spindleTip')"  style="width: 100%">
                                <el-option v-for="item in setting.spindleOptions" :key="item.label" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('lab.sampleName')">
                            <el-input  v-model="setting.sampleName"  clearable style="width: 100%"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('lab.operator')">
                            <el-input v-model="setting.operator" clearable style="width: 100%"></el-input>
                        </el-form-item>
                    </el-form>
                    <el-card shadow="always" >
                        <el-form ref="setting" :inline="true" label-width="auto"  v-for="(item, index) in setting.programs" :key="index">
                            <el-form-item :label='$t("lab.programSettingData") + " " + (index + 1)'>

                            </el-form-item>
                            <el-form-item :label="$t('lab.timeGap')" prop="timeTip">
                                <el-input v-model="item.timeGap" clearable type="number" style="width: 100%">
                                    <template slot="append">S</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item :label="$t('lab.measureTime')" prop="measureTime">
                                <el-input v-model="item.measureTime" clearable type="number" style="width: 100%">
                                    <template slot="append">M</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item :label="$t('lab.rpm')" prop="rpm" v-if="setting.showSpeedSelective">
                              <el-select v-model="item.rpm" filterable clearable style="width: 100%">
                                <el-option v-for="speed in setting.speedOptions" :key="speed.label" :label="speed.label" :value="speed.value"></el-option>
                              </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('lab.rpm')" prop="rpm" v-else>
                              <el-input-number v-model="item.rpm" clearable style="width: 100%"  :precision="1" :min="setting.speedMin" :max="setting.speedMax"></el-input-number>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="text" v-if="setting.programs.length !== 1" icon="el-icon-minus" @click="removeOne(index)"></el-button>
                                <el-button type="text" v-if="index === setting.programs.length - 1" icon="el-icon-plus" @click="addOne"></el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                </el-card>
            </el-col>
        </el-row>

        <el-row style="margin: 10px 0px">
            <el-form :inline="true">
                <el-button-group >
                    <el-button type="success" icon="el-icon-video-pause" @click="stopOp">{{$t('lab.stop')}}</el-button>
                    <el-button type="primary" icon="el-icon-video-play" @click="startOp" >{{$t('lab.start')}}</el-button>
                    <el-button type="success" icon="el-icon-notebook-1" @click="saveOp">{{$t('lab.save')}}</el-button>
                </el-button-group>
                <el-col style="margin: 10px 0px">
                    <el-steps :active="active" finish-status="success">
                        <el-step :title="item" v-for="(item, index) in steps" :key="index"></el-step>
                    </el-steps>
                </el-col>
            </el-form>
        </el-row>

        <el-card shadow="always">
            <div slot="header" class="clearfix">
                <span>{{$t("lab.receiving")}}</span>
            </div>
            <el-descriptions v-for="(item, index) in receiving" :key="index" :title='$t("lab.receiving") + " " +(index + 1)'>
                <el-descriptions-item :label="$t('lab.naindu')" > <el-tag>{{item.niandu}}</el-tag></el-descriptions-item>
                <el-descriptions-item :label="$t('lab.temperture')">{{item.temperture}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.spindle')"> {{setting.spindle  | spindleFormatter}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.rpm')"> {{setting.programs[index].rpm}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.ratio')">{{item.ratio}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.ss')">{{item.ss}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.sr')">{{item.sr}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.m1')" v-if="showSuperAdmin">{{item.m1}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.m2')" v-if="showSuperAdmin">{{item.m2}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.m3')" v-if="showSuperAdmin">{{item.m3}}</el-descriptions-item>
                <el-descriptions-item :label="$t('lab.lastTime')">{{item.timeLeft}}</el-descriptions-item>
            </el-descriptions>
        </el-card>
        <div>
            <highcharts :options="chartOptions" ref="chart"></highcharts>
        </div>
    </div>

</template>

<script>

    import {isEmptyString, toSendValue} from "../../../utils/protocol";
    import {Message} from "element-ui";
    import {getSerialDevice} from "../../../api/searialDevice";
    import {formatMMSS, spindleFormatter, isEmptyStr, delay, isSpeedSelective, getSpeedOptions} from "../../../utils/util";
    import { addProgramData } from '../../../api/programdata'
    import i18n from "../../../i18n";
    import {getModel} from "../../../api/model";

    export default {
        data() {
            return {
                deviceStatus: 0,
                setting: {
                    sampleName: "",
                    model: "",
                    spindleOptions: [],
                    modelOptions: this.$i18n.tc("lab.modelOptions"),
                    spindle: "",
                    speedMin: 0,
                    speedMax: 120,
                    operator:"",
                    programs: [
                        {
                            "timeGap" : "",
                            "rpm" : "",
                            "measureTime" : "",
                        }
                    ],
                    speedOptions:[],
                    showSpeedSelective: false,

                },
                receiving: [
                    {
                        niandu:"",
                        temperture:"",
                        ratio:"",
                        ss:"",
                        sr:"",
                        m1:"",
                        m2:"",
                        m3:"",
                        timeLeft:""
                    }
                ],
                active: 0,
                steps:[],
                timeOutInterval: null,
                chartOptions: {
                    zoomType: 'x',
                    title: {
                        text: this.$i18n.tc("chart.title")
                    },
                    yAxis: {
                        title: {
                            text: this.$i18n.tc("chart.yAxisViscometer")
                        }
                    },
                    xAxis: {
                        title: {
                            text: this.$i18n.tc("chart.xAxisRPM")
                        }
                    },
                    credits:{
                        enabled: false
                    },
                    series:  [{
                        name: i18n.t("chart.xAxisRPM"),
                        data: []
                    }],
                    tooltip: {
                        shared: true,
                        useHTML: true,
                        headerFormat:"",
                        pointFormatter: function () {
                            return this.x +  '<br/><span style="color: '+ this.series.color + '">\u25CF</span> '+
                                this.series.name + ': <b>'+ this.y +'</b><br/>'
                        }
                    },
                    responsive: {
                        rules: [
                            {
                                condition: {
                                    maxWidth: 500
                                },
                                credits:{
                                    enabled: false // 禁用版权信息
                                }
                            }
                        ]
                    }
                }
            }
        },
        filters:{
          spindleFormatter(value) {
            return spindleFormatter(value)
          }
        },
        beforeDestroy() {
            console.log("beforeDestroyLab");
            // this.$store.commit('bSerialPort/CLOSE');
            // delay(500)
        },
        created() {
          this.asyncInit();
        },
        computed: {
            showSuperAdmin() {
                console.info("roles is " + this.$store.state.user.roles);
                return this.$store.state.user.roles == "SUPPERADMIN";
            }
        },
        watch: {
            "$store.state.bSerialPort.niandu":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].niandu = newVal;
                    if (!isEmptyStr(newVal)) {
                        let rpm = this.setting.programs[this.active - 1].rpm;
                        if (this.chartOptions.series[0].data.length === 0) {
                            this.chartOptions.series[0].data.push([rpm, newVal]);
                        } else {
                            let index = 0;
                            let flag = false;
                            for (let i = 0; i < this.chartOptions.series[0].data.length; i++) {
                                if (this.chartOptions.series[0].data[i][0] == rpm) {
                                    index = i;
                                    flag = true;
                                }
                            }

                            if (flag) {
                                this.chartOptions.series[0].data.splice(index, 1);
                            }

                            this.chartOptions.series[0].data.push([rpm, newVal]);

                        }
                    }
                }
            },
            "$store.state.bSerialPort.temperture":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].temperture = newVal;
                }
            },
            "$store.state.bSerialPort.ratio":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].ratio = newVal;
                }
            },
            "$store.state.bSerialPort.ss":{
                deep:true,//深度监听设置为 true
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].ss = newVal;
                }
            },
            "$store.state.bSerialPort.sr":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].sr = newVal;
                }
            },
            "$store.state.bSerialPort.m1":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].m1 = newVal;
                }
            },
            "$store.state.bSerialPort.m2":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].m2 = newVal;
                }
            },
            "$store.state.bSerialPort.m3":{
                deep:true,//深度监听设置为 true
                handler:function(newVal){
                    if (this.receiving.length < this.m3 || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].m3 = newVal;
                }
            },
            "$store.state.bSerialPort.timeLeft":{
                handler:function(newVal){
                    if (this.receiving.length < this.active || this.active === 0) {
                        return;
                    }
                    this.receiving[this.active - 1].timeLeft = formatMMSS(newVal)
                }
            },
            "$store.state.bSerialPort.settingModel":{
                deep:true,
                handler:function(newVal){
                    if (isEmptyString(newVal)) {
                        return;
                    }
                    this.setting.model = newVal;
                    const key = 'lab.spindleOptions.' + newVal;
                    this.setting.spindleOptions = this.$i18n.tc(key);
                    const speedScopeKey = 'lab.speedOptions.' + newVal;
                    const speedScope =  this.$i18n.tc(speedScopeKey);
                    console.info(speedScope);
                    this.setting.speedMin = speedScope[0];
                    this.setting.speedMax = speedScope[1];

                    if (isSpeedSelective(newVal)) {
                      this.setting.showSpeedSelective = true;
                      this.setting.speedOptions = getSpeedOptions(newVal);
                      this.setting.rpm = this.setting.speedOptions[0]["value"];
                    } else {
                      this.setting.showSpeedSelective = false;
                    }
                }
            }
        },
        methods: {
            async asyncInit() {
                let serialData = await getSerialDevice(1);
                await this.$store.commit('bSerialPort/RE_INIT_PORT', {deviceName: serialData.name, baudRate: 9600});

                let modelData = await getModel(1);
                this.setting.model = modelData.name;
                if (!isEmptyString(this.setting.model)) {
                    this.handleModelSelection(this.setting.model);
                }
                delay(500);
                this.findModel();
            },
            handleModelSelection(val) {
                const key = 'lab.spindleOptions.' + val;
                this.setting.spindleOptions = this.$i18n.tc(key);
                const speedScopeKey = 'lab.speedOptions.' + val;
                const speedScope =  this.$i18n.tc(speedScopeKey);
                console.info(speedScope);
                this.setting.speedMin = speedScope[0];
                this.setting.speedMax = speedScope[1];
                if (isSpeedSelective(val)) {
                  this.setting.showSpeedSelective = true;
                  this.setting.speedOptions = getSpeedOptions(val);
                  this.setting.rpm = this.setting.speedOptions[0]["value"];
                } else {
                  this.setting.showSpeedSelective = false;
                }
            },
            addOne() {
                this.setting.programs.push(
                    {
                        "timeGap" : "",
                        "rpm" : "",
                        "measureTime" : "",
                    }
                );
                this.receiving.push(
                    {
                        niandu:"",
                        temperture:"",
                        ratio:"",
                        ss:"",
                        sr:"",
                        m1:"",
                        m2:"",
                        m3:"",
                        timeLeft:""
                    }
                );
            },
            removeOne(index) {
                console.info(index);
                let newPrograms = [];
                let receiving = [];
                for (let i = 0; i < this.setting.programs.length; i ++) {
                    if (i === index) {
                        continue;
                    }
                    newPrograms.push(this.setting.programs[i]);
                    receiving.push(this.receiving[i]);
                }
                this.setting.programs = newPrograms;
                this.receiving = receiving;
            },
            stopOp() {
                let sendValue = toSendValue("82", "6100", [{value: 0, length: 4}]);
                if (this.$store.state.bSerialPort.serialPort === null ) {
                    this.$store.commit('bSerialPort/RE_INIT_PORT', {deviceName: this.$store.state.bSerialPort.deviceName, baudRate: 9600})
                }
                console.info(sendValue);
                this.$store.commit('bSerialPort/SEND_DATA', {value: sendValue, type: 3, action: 'stop'});
                clearTimeout(this.timeOutInterval);

            },
            startOp() {
                clearTimeout(this.timeOutInterval);

                // check data
                let checkPass = true;
                if (isEmptyString(this.setting.spindle) ||
                        isEmptyString(this.setting.model) ||
                        isEmptyString(this.setting.sampleName) ||
                        isEmptyString(this.setting.operator)
                )  {
                    checkPass = false;
                }

                for (let program of this.setting.programs) {
                   if(isEmptyString(program.rpm) ||
                        isEmptyString(program.timeGap)  ||
                        isEmptyString(program.measureTime) ) {
                       checkPass = false;
                   }
                }

                if (!checkPass) {
                    Message.error({
                        message: this.$i18n.tc("lab.checkinfoError"),
                        showClose: true
                    });
                    return;
                }



                let size = this.setting.programs.length;
                this.steps = [];
                this.receiving = [];
                for (let i = 0; i < this.chartOptions.series.length; i++) {
                    this.chartOptions.series[i].data = [];
                }

                for (let i = 0; i < size; i++) {
                    this.steps.push( this.$i18n.tc("lab.programStepTitle") +  (i + 1));
                    this.receiving.push(
                        {
                            niandu:"",
                            temperture:"",
                            ratio:"",
                            ss:"",
                            sr:"",
                            m1:"",
                            m2:"",
                            m3:"",
                            timeLeft:""
                        }
                    );
                }
                this.steps.push(this.$i18n.tc("lab.programStepStop"));
                this.active = 0;
                this.start();
            },
            start() {
                console.info("current active" + this.active);
                this.active = this.active + 1;
                let size = this.steps.length;
                if (size == this.active) {
                    Message.info({
                        message: this.$i18n.tc("lab.programStop"),
                        showClose: true
                    });
                    this.stopOp();
                    return;
                }
                let programData  = this.setting.programs[this.active - 1];
                let sendValue = toSendValue("82", "5200", [{value: this.setting.spindle, length: 4}, {value: programData.rpm * 10, length: 4}, {value: programData.timeGap, length: 4}, {value: programData.measureTime, length: 4}]);
                if (this.$store.state.bSerialPort.serialPort === null ) {
                    this.$store.commit('bSerialPort/RE_INIT_PORT', {deviceName: this.$store.state.bSerialPort.deviceName, baudRate: 9600})
                }
                console.info(sendValue);
                this.$store.commit('bSerialPort/SEND_DATA', {value: sendValue, type: 3, action: 'data'});


                delay(500)

                let startValue = toSendValue("82", "6100", [{value: 1, length: 4}]);
                console.info(startValue);
                this.$store.commit('bSerialPort/SEND_DATA', {value: startValue, type: 3, action: 'start'});

                this.timeOutInterval = setTimeout(
                    this.start,
                    programData.measureTime * 60 * 1000 + 10000
                );
            },
            async saveOp(){
                if (this.$store.state.bSerialPort.status) {
                    Message.warning({
                        message: this.$i18n.tc("lab.dataCannotSave"),
                        showClose: true
                    });
                    return;
                }
                await addProgramData({
                    "sample": this.setting.sampleName,
                    "username": this.setting.operator,
                    "model": this.setting.model,
                    "spindle": this.setting.spindle,
                    "setting": this.setting,
                    "receiving": this.receiving,
                    "createTime": new Date().getTime(),
                    "createOn": this.$store.state.user.id
                });
                Message.success({
                    message : this.$i18n.tc('lab.dataSave'),
                    showClose: true
                });
            },
            findModel(){
                let sendValue = toSendValue("82", "6100", [{value: 2, length: 4}]);
                if (this.$store.state.bSerialPort.serialPort === null ) {
                    this.$store.commit('bSerialPort/RE_INIT_PORT', {deviceName: this.$store.state.bSerialPort.deviceName, baudRate: 9600})
                }
                console.info(sendValue);
                this.$store.commit('bSerialPort/SEND_DATA', {value: sendValue, type: 3, action: 'findAction'});
            },
        }
    }
</script>

<style scoped>

</style>
